import {
  getUserById,
  updatePwdByOld,
  editUser
} from '@/api/user'
import Crypto from '@/utils/crypto'

const getDefaultState = () => {
  return {
    userInfo: {},
    tenantName: ''
  }
}

const state = getDefaultState()

const getters = {
  userId: (state, getters, rootState) => rootState.user.userId
}

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // 修改用户信息
  async onUpdateUser({ commit, rootState }, payload) {
    const { userName } = payload
    const { success } = await editUser(payload)
    if (success) {
      rootState.user.userName = userName
    }
  },
  // 修改密码
  async onUpdatePwd({ commit, getters }, payload) {
    const { newPassword, oldPassword } = payload
    const cryptoNewPassword = await Crypto(newPassword)
    const cryptoOldPassword = await Crypto(oldPassword, true)
    await updatePwdByOld({
      userId: getters.userId,
      newPassword: cryptoNewPassword,
      oldPassword: cryptoOldPassword
    })
  },
  // 获取用户详情
  async getUserInfo({ getters }) {
    const { retData } = await getUserById(getters.userId)
    return retData
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
